package com.example.framework.security.core.util;

import com.example.framework.security.core.LoginUser;
import com.example.framework.web.core.util.WebFrameworkUtils;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.ObjectUtils;

import java.util.Objects;

public class SecurityFrameworkUtils {

    /**
     * HEADER 认证头 value 的前缀
     */
    public static final String AUTHORIZATION_BEARER = "Bearer ";

    private SecurityFrameworkUtils() {
    }

    /**
     * 从请求头/请求参数/cookie中解析获取jwt
     */
    @Nullable
    public static String obtainAuthorization(HttpServletRequest request, String tokenName) {
        String token = request.getHeader(tokenName);
        if (ObjectUtils.isEmpty(token)) {
            token = request.getParameter(tokenName);
        }
        if (ObjectUtils.isEmpty(token) && Objects.nonNull(request.getCookies())) {
            for (Cookie cookie : request.getCookies()) {
                if (tokenName.equalsIgnoreCase(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
        }
        if (ObjectUtils.isEmpty(token)) {
            return null;
        }
        return token.replaceFirst(AUTHORIZATION_BEARER, "");
    }

    /**
     * 获取当前用户
     *
     * @return 当前用户
     */
    @Nullable
    public static LoginUser getLoginUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return authentication.getPrincipal() instanceof LoginUser ? (LoginUser) authentication.getPrincipal() : null;
    }


    /**
     * 获得当前用户的编号，从上下文中
     *
     * @return 用户编号
     */
    @Nullable
    public static String getLoginUserId() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getUsername() : null;
    }

    @Nullable
    public static String getLoginUserName() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getNickname() : null;
    }

    @Nullable
    public static String getCountryId() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getCountryId() : null;
    }

    /**
     * 获得当前认证信息
     *
     * @return 认证信息
     */
    public static Authentication getAuthentication() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null) {
            return null;
        }
        return context.getAuthentication();
    }

    /**
     * 设置当前用户
     *
     * @param loginUser 登录用户
     * @param request   请求
     */
    public static void setLoginUser(LoginUser loginUser, HttpServletRequest request) {
        // 创建 Authentication，并设置到上下文
        Authentication authentication = buildAuthentication(loginUser, request);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 额外设置到 request 中，用于 ApiAccessLogFilter 可以获取到用户编号；
        // 原因是，Spring Security 的 Filter 在 ApiAccessLogFilter 后面，在它记录访问日志时，线上上下文已经没有用户编号等信息
        WebFrameworkUtils.setLoginUserId(request, loginUser.getUsername());
    }

    /**
     * 参考 {@link AbstractUserDetailsAuthenticationProvider#createSuccessAuthentication(Object, Authentication, UserDetails)}
     *
     * @param loginUser 登录用户信息
     * @param request   请求
     * @return the successful authentication token
     */
    private static Authentication buildAuthentication(LoginUser loginUser, HttpServletRequest request) {
        UsernamePasswordAuthenticationToken authenticationToken = UsernamePasswordAuthenticationToken.authenticated(
                loginUser, null, loginUser.getAuthorities());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        return authenticationToken;
    }
}
